package com.liu.communitysystemend.security.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.liu.communitysystemend.security.component.JwtTokenUtils;
import com.liu.communitysystemend.security.exception.TokenIsExpiredException;
import com.liu.communitysystemend.utils.JsonResult;
import com.liu.communitysystemend.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * @author liu
 * @create 2023-02-18 10:21
 */
@Slf4j
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    private RedisUtil redisUtil;
    private JwtTokenUtils jwtTokenUtils;

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletContext servletContext = request.getServletContext();
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        redisUtil = context.getBean(RedisUtil.class);
        jwtTokenUtils = context.getBean(JwtTokenUtils.class);

        String tokenHeader = request.getHeader(jwtTokenUtils.TOKEN_HEADER);
        if (tokenHeader==null ||!tokenHeader.startsWith(jwtTokenUtils.TOKEN_PREFIX)){
            chain.doFilter(request,response);
            return;
        }
        try {
            SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
        }catch (TokenIsExpiredException e){
            log.error(e.toString()+" : "+e.getMessage());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            String reason = JsonResult.failed(1040, e.getMessage());
            response.getWriter().write(new ObjectMapper().writeValueAsString(reason));
            response.getWriter().flush();
            return;
        }
        super.doFilterInternal(request, response, chain);


    }

    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) throws TokenIsExpiredException {
        String token = tokenHeader.replace(jwtTokenUtils.TOKEN_PREFIX, "");
        Boolean expiration = redisUtil.hasKey(tokenHeader);
        if (Boolean.FALSE.equals(expiration)){
            throw new TokenIsExpiredException("token过期,请重新登录");
        }else {
            String username=jwtTokenUtils.getUsername(token);
            String role = jwtTokenUtils.getUserRole(token);
            if (username!=null){
                redisUtil.setKeyExpire(tokenHeader,720000000L);
                return new UsernamePasswordAuthenticationToken(username,null, Collections.singleton(new SimpleGrantedAuthority(role)));
            }
        }
        return null;
    }
}
